#include <WindowsX.h>
#include "Plugin.h"
#include <stdio.h>

static LRESULT CALLBACK PluginWinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
	switch (msg) 
	{

	 case WM_TIMER:
		 {
			CPlugin * p = (CPlugin *)GetWindowLong(hWnd, GWL_USERDATA);
			if (p)
				p->tick();
		 }
		 break;

	 default:
		 break;
	}

	return DefWindowProc(hWnd, msg, wParam, lParam);
}


CPlugin::CPlugin(void)
: m_hWnd(NULL)
, m_pOldProc(NULL)
{
}

CPlugin::~CPlugin(void)
{
}

int CPlugin::init(HWND hwnd)
{
	if (m_hWnd)
		return 0;

	if (!hwnd)
		return -1;

	if (!m_hWnd)
	{
		m_hWnd = hwnd;
		m_pOldProc = SubclassWindow(m_hWnd, (WNDPROC)PluginWinProc);

		SetWindowLong(m_hWnd, GWL_USERDATA, (LONG)this);

		SetTimer(m_hWnd, 1234, 100, 0);

	}

	return 0;
}

int CPlugin::destory()
{
	if (m_hWnd)
	{
		KillTimer(m_hWnd, 1234);
		
		SubclassWindow(m_hWnd, m_pOldProc);
		m_hWnd = NULL;

		return 0;
	}

	return -1;
}

void CPlugin::tick()
{ 
	HDC hdc = GetDC(m_hWnd);
	if (hdc)
	{
		char buf[16];
		static int n = 0;
		itoa(++n, buf, 10);

		TextOut(hdc, 0, 0, buf, strlen(buf));

		ReleaseDC(m_hWnd, hdc);
	}
}